package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity implements Runnable {
    float dollar_rate,euro_rate,won_rate;
    TextView result;
    EditText rmb;
    Handler handler;
    public static final String TAG="main";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        result=findViewById(R.id.hi);
        rmb=findViewById(R.id.input);

        /*SharedPreferences sharedPreferences=getSharedPreferences("myrate",Activity.MODE_PRIVATE);
        //获取SharedPreferences对象
        dollar_rate=sharedPreferences.getFloat("new_dollar_rate_key",1.2f);
        euro_rate=sharedPreferences.getFloat("new_euro_rate_key",0.3f);
        won_rate=sharedPreferences.getFloat("new_won_rate_key",0.2f);*/

        //将数据存入myrate中
        Thread t=new Thread(this);//开启子线程
        t.start();
        handler=new Handler(){
            public void handleMessage(Message msg){
                if(msg.what==5){
                    Bundle bundle=(Bundle) msg.obj;
                    dollar_rate=bundle.getFloat("web-dollar");
                    euro_rate=bundle.getFloat("web-euro");
                    won_rate=bundle.getFloat("web-won");
                    result.setText("get web ok");
                }
                super.handleMessage(msg);
            }
        };

    }

        public void mycilck(View btm){
        if(rmb.length()==0){
            Toast.makeText(this,"请输入数值",Toast.LENGTH_SHORT).show();
            return;
        }
        String str=rmb.getText().toString();
        float input=Float.parseFloat(str);
        float r=0.0f;
        if(btm.getId()==R.id.dollar_btm){
            r=input*dollar_rate;
        }
        else if(btm.getId()==R.id.euro_btm){
            r=input*euro_rate;
        }
        else{
            r=input*won_rate;
        }
        result.setText("结果"+r);
    }
    public void open(View btn){
        openconfig();
    }

    private void openconfig() {
        Intent config = new Intent(this, configActivity2.class);
        config.putExtra("dollar_rate_key", dollar_rate);
        config.putExtra("euro_rate_key", euro_rate);
        config.putExtra("won_rate_key", won_rate);
        //startActivity(config);
        startActivityForResult(config, 1);
        //打开返回数据窗口
    }

    public boolean onCreateOptionsMenu(Menu menu){  //启用菜单项
        getMenuInflater().inflate(R.menu.rate,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) { //处理菜单事件
        if(item.getItemId()==R.id.menu_set){
            openconfig();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
        if(requestCode==1&&resultCode==2){
            Bundle bundle=data.getExtras();
            //dollar_rate=bundle.getFloat("new_dollar_rate_key",1.2f);
            //euro_rate=bundle.getFloat("new_euro_rate_key",0.3f);
            //won_rate=bundle.getFloat("new_won_rate_key",0.2f);
            Log.i(TAG, "onActivityResult: dollar_rate="+dollar_rate);
            SharedPreferences sharedPreferences=getSharedPreferences("myrate",Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor=sharedPreferences.edit();
            //editor可以修改保存myrate中key相同的数据
            editor.putFloat("new_dollar_rate_key",dollar_rate);
            editor.putFloat("new_euro_rate_key",euro_rate);
            editor.putFloat("new_won_rate_key",won_rate);
            editor.apply();
        }
    }
    public String inputStream2String(InputStream inputStream)throws IOException{
        //创建一个将输入流数据转化为String类型的方法
        final int bufferSize=1024;
        final char[] buffer=new char[bufferSize];
        final StringBuilder out=new StringBuilder();
        Reader in=new InputStreamReader(inputStream,"gb2312");
        while (true){
            int rsz=in.read(buffer,0,buffer.length);
            if(rsz<0){
                break;
            }
            out.append(buffer,0,rsz);
        }
        return out.toString();
    }

    @Override
    public void run() {
        Log.i(TAG, "run: run()......");

        /*URL url= null; //记得在manifests中加权限
        try {
            url = new URL("https://www.usd-cny.com/bankofchina.htm");
            HttpURLConnection http=(HttpURLConnection) url.openConnection();//尝试连接网页
            InputStream in=http.getInputStream();//获取输入流的数据in
            String html=inputStream2String(in);//将输入流数据转化为String类型
            Log.i(TAG, "run: html="+html);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(3000);
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }

         */
        try {
            Document doc = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
            String title=doc.title();
            Log.i(TAG, "run: title"+doc.title());
            //获取td元素
            /*Elements tds=doc.getElementsByTag("td");
            for (Element td:tds){
                Log.i(TAG, "run: td="+td.text());
            }
             */
            /*Elements trs=doc.getElementsByTag("tr");
            for(Element tr:trs){
                Elements tds=tr.getElementsByTag("td");
                if(tds.size()>0){
                    String td1=tds.get(0).text();
                    String td2=tds.get(5).text();
                    Log.i(TAG, "run: "+td1+"==>"+td2);
                }
            }*/
            Element table=doc.selectFirst("table");
            Element d_td=table.selectFirst("tr:nth-child(27) > td:nth-child(4)");//需要数是第几行第几列都是从1开始
            String tb1=d_td.text();
            Element u_td=table.selectFirst("tr:nth-child(8) > td:nth-child(4)");
            String tb2=u_td.text();
            Element w_td=table.selectFirst("tr:nth-child(14) > td:nth-child(4)");
            String tb3=w_td.text();
            /*Element table=doc.selectFirst("table");
            String tb1=table.selectFirst("body > section > div > div > article > table > tbody > tr:nth-child(27) > td:nth-child(4)").text();
            String tb2=table.selectFirst("body > section > div > div > article > table > tbody > tr:nth-child(8) > td:nth-child(4)").text();
            String tb3=table.selectFirst("body > section > div > div > article > table > tbody > tr:nth-child(14) > td:nth-child(4)").text();*/
            Log.i(TAG, "run: td1+"+tb1);
            Log.i(TAG, "run: td2+"+tb2);
            Log.i(TAG, "run: td3+"+tb3);
            Bundle bundle=new Bundle();
            float d_rate_td=Float.valueOf(tb1);
            float u_rate_td=Float.valueOf(tb2);
            float w_rate_td=Float.valueOf(tb3);
            bundle.putFloat("web-dollar",100/d_rate_td);
            bundle.putFloat("web-euro",100/u_rate_td);
            bundle.putFloat("web-won",100/w_rate_td);
            Message msg=handler.obtainMessage(5);
            msg.obj=bundle;//可以放任何数据
            handler.sendMessage(msg);//handler 可以理解为快递系统
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}